/**
 * 
 */
package ar.edu.unicen.exa.oop.bbquery.forum_service.crawler;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Este crawler permite obtener un DOM desde algun lugar.
 * 
 * @author nicolas
 * 
 */
public class DOMCrawler implements Crawler {

	private static Logger log = LoggerFactory.getLogger(DOMCrawler.class);

	private HttpClient client;
	private GetMethod meth;

	public DOMCrawler(String URL) {

		log.info("Creating HTTPClient");
		client = new HttpClient();
		client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler());
		meth = new GetMethod(URL);
		log.info("Creating SAXBuilder");

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see ar.edu.unicen.exa.oop.bbquery.forum_service.IForumFetcher#retrive()
	 */
	public InputStream retrive(CrawlerAddress crwlr) throws IOException  {

		touchAddress(crwlr);
		client.executeMethod(meth);
		return meth.getResponseBodyAsStream();

	}

	/**
	 * @param crwlr
	 * @return
	 */
	private void touchAddress(CrawlerAddress crwlr) {
		meth.setFollowRedirects(true);
		meth.setPath(meth.getPath() + '/' + crwlr.getPath());
		meth.setQueryString(crwlr.getQuery());
		try {
			log.info("GET URI : " + meth.getURI());
		} catch (URIException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


}
